package com.ilink.groundservice.controller.AiX;/**
 * <h3>iLink-java-backend-zhangbo2</h3>
 *
 * @Description <p>专区前端接口</p>
 * @Author ZhangBo
 * @Date 2025-01-17 11:45
 **/

import com.ilink.groundservice.entity.PO.AiX.AiXArea;
import com.ilink.groundservice.entity.VO.AiX.AiXAreaResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXAreaSceneInfo;
import com.ilink.groundservice.entity.VO.AiX.UserPermissionResponse;
import com.ilink.groundservice.service.AiX.AiXAreaService;
import com.ilink.ilinkapi.client.UserServiceClient;
import com.ilink.ilinkapi.dto.ground.AiX.AiXAreaInsertRequset;
import com.ilink.ilinkapi.dto.ground.AiX.AiXAreaUpdateRequest;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.domain.User;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.utils.BeanUtils;
import com.ilink.ilinkcommon.utils.UserContext;

import java.util.Arrays;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ClassName AiXAreaController
 * @Description TODO
 * @Author ZhangBo
 * @Date 2025-01-17 11:45
 **/
@Slf4j
@RequestMapping("/ground/aix/area")
@RestController
@RequiredArgsConstructor
public class AiXAreaController {
    private final AiXAreaService aiXAreaService;
    private final UserServiceClient userServiceClient;
    @MethodLog("微场景权限")
    @PostMapping("/check")
    public R checkUserPermissions(@RequestParam(required = false) Long sceneId) {
        try {
            if (sceneId == null) {
                sceneId = 0L;
            }
            String userId = UserContext.getUserId();
            UserPermissionResponse response = aiXAreaService.checkUserPermissions(sceneId, userId);
            return R.ok("权限检查成功", response);
        } catch (Exception e) {
            log.error("权限检查失败", e);
            return R.error("权限检查失败");
        }
    }

    @MethodLog("获取专区内微场景所有出品人")
    @GetMapping("/get_all_scene_authors")
    public R getAllSceneAuthors(@RequestParam Long areaId) {
        try {
            List<User> authors = aiXAreaService.getAllSceneAuthors(areaId);
            return R.ok("获取专区内微场景所有出品人成功", authors);
        } catch (Exception e) {
            log.error("获取专区内微场景所有出品人失败", e);
            return R.error("获取专区内微场景所有出品人失败");
        }
    }

    @MethodLog("获取专区内微场景出品人具体信息")
    @GetMapping("/get_scene_author_info")
    public R getSceneAuthorInfo(@RequestParam Long areaId) {
        try {
            List<AiXAreaSceneInfo> info = aiXAreaService.getSceneAuthorInfo(areaId);
            return R.ok("获取专区内微场景出品人具体信息成功", info);
        } catch (Exception e) {
            log.error("获取专区内微场景出品人具体信息失败", e);
            return R.error("获取专区内微场景出品人具体信息失败");
        }
    }

    /**
     * @Author ZhangBo
     * @Description 统计某用户专区下的所有微场景下所有阶段下的作业分数和
     * @Date 21:06 2025/1/19
     * @Param [areaId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("统计某用户的所有微场景下所有阶段下的作业分数和")
    @GetMapping("/get_phase_work_score_sum/{areaId}")
    public R getPhaseWorkScoreSum(@PathVariable Long areaId) {
        try {
            String userId = UserContext.getUserId(); // 获取当前用户ID
            return aiXAreaService.getPhaseWorkScoreSum(userId,areaId);
        } catch (Exception e) {
            log.error("统计作业分数和失败，areaId: " + areaId, e);
            return R.error("统计作业分数和失败");
        }
    }

    /**
     * @Author ZhangBo
     * @Description 对专区下所有用户的作业分数进行排序
     * @Date 21:06 2025/1/19
     * @Param [areaId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("对专区下所有用户的作业分数进行排序")
    @GetMapping("/get_area_work_score_sort")
    public R getAreaWorkScoreSort(@RequestParam Long areaId,
        @RequestParam Long num) {
        try {
            return aiXAreaService.getAreaWorkScoreSort(areaId, num);
        } catch (Exception e) {
            log.error("对专区下所有用户的作业分数进行排序失败，areaId: " + areaId, e);
            return R.error("对专区下所有用户的作业分数进行排序失败");
        }
    }
    
    // 对专区下的所有报名记录进行排序
    @MethodLog("对专区下的所有报名记录进行排序")
    @GetMapping("/get_area_sign_up_sort")
    public R getAreaSignUpSort(@RequestParam Long areaId,
        @RequestParam Long num) {
        try {
            return aiXAreaService.getAreaSignUpSort(areaId, num);
        } catch (Exception e) {
            log.error("对专区下的所有报名记录进行排序失败，areaId: " + areaId, e);
            return R.error("对专区下的所有报名记录进行排序失败");
        }
    }


    @MethodLog("插入新的专区数据")
    @PostMapping("/insert_area")
    public R insertProject(AiXAreaInsertRequset requset){
        if (!isTeacher(UserContext.getUserId())) {
            return R.error("无教师权限");
        }
        try {
            aiXAreaService.insertArea(requset);
            return R.ok("专区插入成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("更新专区数据")
    @PostMapping("/update_area")
    public R updateArea(@RequestBody AiXAreaUpdateRequest request) {
        if (!isTeacher(UserContext.getUserId())) {
            return R.error("无教师权限");
        }
        try {
            aiXAreaService.updateAreaBase(request);
            return R.ok("专区更新成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }
    @MethodLog("更新专区封面图")
    @PostMapping("/update_area_cover")
    public R updateAreaCover(MultipartFile file, Long areaId ) {
        if (!isTeacher(UserContext.getUserId())) {
            return R.error("无教师权限");
        }
        try {
            aiXAreaService.updateAreaCover(file, areaId);
            return R.ok("专区封面图更新成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("获取专区数据")
    @GetMapping("/get_area/{areaId}")
    public R getArea(@PathVariable Long areaId) {
        try {
            AiXAreaResponse response = aiXAreaService.getArea(areaId);
            return R.ok("专区获取成功", response);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("获取专区最常用的12个标签标签")
    @GetMapping("/get_area_tags")
    public R getAreaTags(@RequestParam Long areaId) {
        try {
            List<String> tags = aiXAreaService.getAreaTags(areaId);
            return R.ok("专区最常用的12个标签", tags);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("获取专区列表")
    @GetMapping("/get_area_list")
    public R getAreaList() {
        try {
            List<AiXArea> areas = aiXAreaService.getAreaList();
            return R.ok("专区列表", areas);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    private boolean isTeacher(String userId) {
        R whoami = userServiceClient.whoami(userId);
        HttpStatus status = HttpStatus.valueOf(whoami.getCode());
        if (!status.is2xxSuccessful()) {
            log.error(String.format("获取用户信息失败，用户ID: %s", userId));
            return false;
        }
        User userDetail = BeanUtils.copyBean(whoami.getData(), User.class);
        String userType = userDetail.getUserType();
        return Arrays.asList("BIAdmin", "L0101", "L0107", "L0108", "L0109").contains(userType);
    }
}
